package com.longrise.android.byjk.plugins.dealsituation.course.certificate;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BasePresenter;
import com.longrise.android.byjk.common.FolderConstants;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.dealsituation.course.cache.CacheTask;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.PrintLog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


/**
 * Created by godliness on 2017/4/27.
 */

public class CertPresenter extends BasePresenter<CertView> {

    private static final String TAG = "CertPresenter";

    /**
     * 请求图片地址
     */
    private final int mLoadImageType = 0;
    /**
     * 同步学习记录
     */
    private final int mUploadType = 1;

    private int mCurrentParseType = mLoadImageType;

    private int mResultState = 0;

    private boolean mFinished;

    @Override
    protected void init() {

    }

    public void setFinished() {
        mFinished = true;
    }

    /**
     * 请求证件url
     */
    public void loadImage() {
        VideoParams vp = mView.getParams();
        if (vp == null) {
            return;
        }
        mCurrentParseType = mLoadImageType;
        String api = vp.mType == CertActivity.CertType.TYPE_CERT ? "bbt_course_sTrainCertImg" : "bbt_course_sTrainRecordImg";
        EntityBean bean = generateParams(vp);
        EntityBean reqBean = new EntityBean();
        reqBean.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, api, reqBean, mCallListener);
    }

    /**
     * 同步学习记录
     */
    public void toUploadRecord() {
        VideoParams vp = mView.getParams();
        if (vp == null) {
            return;
        }
        mCurrentParseType = mUploadType;
        mView.updateUploadBtnState(false);
        mView.showLoadingDialog();
        EntityBean bean = generateParams(vp);
        bean.set("signupid", vp.mTrainsiqnupid);
        EntityBean reqBean = new EntityBean();
        reqBean.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, "bbt_course_resumtraininfo", reqBean, mCallListener);
    }

    private EntityBean generateParams(VideoParams vp) {
        EntityBean bean = new EntityBean();
        bean.set("planid", vp.mCourseId);
        bean.set("studentno", vp.mStudentNo);
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        return bean;
    }

    private LoadDataManager.OnRequestCallListener mCallListener = new LoadDataManager.OnRequestCallListener() {
        @Override
        public void onSuccess(String key, String service, Object result) {
            if (mFinished) {
                return;
            }
            if (result instanceof EntityBean) {
                EntityBean resultBean = (EntityBean) result;
                mResultState = resultBean.getInt("resultstate");
                if (mResultState != 1) {
                    mView.showToast(resultBean.getString("resultdesc"));
                    mView.onError();
                    return;
                }
                if (mCurrentParseType == mLoadImageType) {
                    parseImage(resultBean);
                    return;
                }
                parseUpload(resultBean);
            }
        }

        @Override
        public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
            mView.showToast(mContext.getString(R.string.nonetwork));
            mView.onError();
        }

        @Override
        public void onFinished(String key, String service) {
            if (mCurrentParseType == mUploadType) {
                if (mResultState != 1) {
                    mView.updateUploadBtnState(true);
                }
                mView.dismissLoadingDialog();
            }
        }
    };

    /**
     * 加载图片地址
     */
    public void toLoadImage(final String url) {
        Glide.with(mContext).load(url).into(new SimpleTarget<GlideDrawable>() {
            @Override
            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                mView.setImageDrawable(resource);
                mView.parse(url);
                mView.dismissLoadingDialog();
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                super.onLoadFailed(e, errorDrawable);
                mView.showToast("图片加载失败了,请稍后再试...");
                mView.dismissLoadingDialog();
            }
        });
    }

    /**
     * 保存图片到sd卡
     */
    public void saveToFile(ImageView drawable) {
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if (!sdCardExist) {
            mView.showToast(mContext.getString(R.string.sd_is_none));
            return;
        }
        CacheTask.submit(new SaveRunnable(drawable));
    }

    /**
     * 解析同步学习记录
     */
    private void parseUpload(EntityBean resultBean) {
        mView.showToast(resultBean.getString("resultdesc"));
    }

    /**
     * 解析证书图片地址
     */
    private void parseImage(EntityBean resultBean) {
        String imageUrl = resultBean.getString("result");
        if (TextUtils.isEmpty(imageUrl)) {
            mView.showToast("课件配置节点异常");
            mView.onError();
            return;
        }
        toLoadImage(imageUrl);
    }

    private class SaveRunnable implements Runnable {

        private File mSavePath;
        private ImageView mImageSave;

        private final StringBuilder mNameBuilder = new StringBuilder();

        public SaveRunnable(final ImageView imageView) {
            this.mImageSave = imageView;
        }

        @Override
        public void run() {
            Bitmap drawable = getDrawingCache(mImageSave);
            if (drawable == null) {
                return;
            }
            File file = new File(FolderConstants.SAVE_PHOTO);
            if (!file.exists()) {
                file.mkdir();
            }
            FileOutputStream fos = null;
            try {
                fos = getFileOutputStream(drawable, file);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (drawable != null) {
                        drawable.recycle();
                    }
                    if (fos != null) {
                        fos.flush();
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            notifySystemMedia();
        }

        /**
         * 通知系统图库更新
         */
        private void notifySystemMedia() {
            if (mSavePath == null || mImageSave == null) {
                return;
            }
            //通知系统图库更新
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(mSavePath);
            intent.setData(uri);
            mContext.sendBroadcast(intent);
            PrintLog.e(TAG, "sendBroadcast");

        }

        /**
         * 将要保存的图片保存到指定路径
         */
        @NonNull
        private FileOutputStream getFileOutputStream(Bitmap drawable, File file) throws FileNotFoundException {
            FileOutputStream fos;
            String name = generateName();
            mSavePath = new File(file.getAbsolutePath(), name);
            fos = new FileOutputStream(mSavePath);
            drawable.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            //图片插入到系统图库
            MediaStore.Images.Media.insertImage(mContext.getContentResolver(), mSavePath.getAbsolutePath(), name, "bb");
            mImageSave.post(new Runnable() {
                @Override
                public void run() {
                    mView.showToast(mContext.getString(R.string.savepic_success) + FolderConstants.SAVE_PHOTO);
                }
            });
            return fos;
        }

        /**
         * 获取要保存图片的位图
         */
        private Bitmap getDrawingCache(ImageView iv) {
            iv.setDrawingCacheEnabled(true);
            iv.buildDrawingCache();
            Bitmap drawable = Bitmap.createBitmap(iv.getDrawingCache());
            iv.setDrawingCacheEnabled(false);
            return drawable;
        }

        /**
         * 生成图片名字
         */
        private String generateName() {
            VideoParams vp = mView.getParams();
            int type = mView.getCertType();
            mNameBuilder.setLength(0);
            if (type == CertActivity.CertType.TYPE_CERT) {
                return mNameBuilder.append("cert_").append(vp.mStudentNo).append(".jpg").toString();
            }
            return mNameBuilder.append("record_").append(vp.mStudentNo).append(".jpg").toString();
        }
    }
}
